﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiteParser.Core.Configuration;
using System.Reflection;
using System.Runtime.Remoting;

namespace SiteParser.Core.Formatters
{
	public static class FormattersMapper
	{
		private static bool isInitialized = false;
		private static IDictionary<string, IFormatter> formattersMap;
		private static IFormatter defaultFormatter;

		public static IFormatter GetFormatter(string formatterName) {
			if (!isInitialized) {
				Initialize();
			}

			if (string.IsNullOrEmpty(formatterName)) {
				return defaultFormatter;
			}

			return formattersMap.ContainsKey(formatterName) ? formattersMap[formatterName] : defaultFormatter;
		}

		private static void Initialize() {
			defaultFormatter = new DefaultFormatter();
			formattersMap = new Dictionary<string, IFormatter>();

			if (ParserConfigSection.Instance.FormattersConfig != null) {
				foreach (FormatterItemConfiguration formatterConfig in ParserConfigSection.Instance.FormattersConfig) {
					string formatterTypeValue = formatterConfig.Type;
					string formatterName = formatterConfig.Name;
					if (!string.IsNullOrEmpty(formatterTypeValue) && !string.IsNullOrEmpty(formatterName))
					{
						string[] activatorsParams = formatterTypeValue.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

						if (activatorsParams.Length >=2 )
						{
							string assemblyName = activatorsParams[0];
							string formatterType = activatorsParams[1];

							ObjectHandle formatterHandle = Activator.CreateInstance(assemblyName, formatterType);
							IFormatter formatter = (IFormatter)formatterHandle.Unwrap();

							formattersMap[formatterName] = formatter;
						}
					}
				}
			}

			isInitialized = true;
		}
	}
}
